package com.zzsy.carosshopprojects.activitys.home.mainpage.member.memberconsum.order;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.king.base.util.ToastUtils;
import com.zzsy.carosshopprojects.R;
import com.zzsy.carosshopprojects.base.BaseFragment;
import com.zzsy.carosshopprojects.base.ConfigureFile;
import com.zzsy.carosshopprojects.bean.ActivityBean;
import com.zzsy.carosshopprojects.bean.CouponChoseBean;
import com.zzsy.carosshopprojects.util.AlgorithmUtil;
import com.zzsy.carosshopprojects.util.DataUtil;
import com.zzsy.carosshopprojects.util.SerializableMap;
import com.zzsy.carosshopprojects.util.StringUtils;
import com.zzsy.carosshopprojects.util.ViewBgUtil;

import java.util.HashMap;
import java.util.Map;

import androidx.constraintlayout.widget.ConstraintLayout;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * 会员消费订单详情
 */
public class OrderDetailFragment extends BaseFragment {
    public static OrderDetailFragment newInstance(String memberId, String amount, String usedOil, String productId, String password, String paySwitch
            , String oilsPrice, String payType, String balance, String memberCardId, String productInfoId, String memberType, String parentId,
                                                  String oilPrice, String isUseCoupon) {
        OrderDetailFragment orderDetailFragment = new OrderDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putString("memberId", memberId);
        bundle.putString("amount", amount);
        bundle.putString("usedOil", usedOil);
        bundle.putString("productId", productId);
        bundle.putString("password", password);
        bundle.putString("paySwitch", paySwitch);
        bundle.putString("oilsPrice", oilsPrice);
        bundle.putString("payType", payType);
        bundle.putString("balance", balance);
        bundle.putString("memberCardId", memberCardId);
        bundle.putString("productInfoId", productInfoId);
        bundle.putString("memberType", memberType);
        bundle.putString("parentId", parentId);
        bundle.putString("oilPrice", oilPrice);
        bundle.putString("isUseCoupon", isUseCoupon);
        orderDetailFragment.setArguments(bundle);
        return orderDetailFragment;
    }

    @BindView(R.id.cl)
    ConstraintLayout cl_top;
    @BindView(R.id.tv_pay)
    TextView tv_pay;
    @BindView(R.id.tv_sf_amount)
    TextView tvSFAmount;  //实付金额
    @BindView(R.id.tv_yf_amount)
    TextView tvOrderAmount;  //订单金额
    @BindView(R.id.tv_oils_nums)
    TextView tvOilsNums;  //油品号
    @BindView(R.id.tv_activity)
    TextView tvActivity;  //活动折扣
    @BindView(R.id.tv_coupon_select)
    TextView tvCouponSelect;  //显示优惠券信息
    @BindView(R.id.tv_cpoun_num)
    TextView tvCpounNum;   //优惠券选择张数
    @BindView(R.id.ll_view04)
    LinearLayout llCounpList;  //选择优惠券按钮
    @BindView(R.id.lyActivity)
    LinearLayout lyActivity;  //活动View
    private String orderAmount;//订单金额
    private String memberType;//会员类型
    private OrderDetailMode orderDetailMode;
    private int actualPayment = 0;//实付金额
    private String oilPrice;//油价
    private String isUseCoupon;//是否可以使用优惠券
    private String memberCardId;//会员卡ID
    private String memberId;//会员ID
    private String productId;
    private String productInfoId;
    private String usedOil;
    private String paySwitch;
    private String parentId;
    private Map<String, String> map = new HashMap<>();

    @Override
    protected int initLayout() {
        return R.layout.fg_orderdetail;
    }

    @Override
    protected void initView(View view) {
        initTitle(view, getResources().getString(R.string.OrderDetail), getActivity());
        cl_top.setBackground(ViewBgUtil.setBg(10, Color.parseColor(ConfigureFile.ColorWhite)));
        tvCpounNum.setBackground(ViewBgUtil.setWidthBg(360, 2, Color.parseColor(ConfigureFile.ColorWhite), Color.parseColor(ConfigureFile.ColorSystem)));
        // tv_pay.setBackground(ViewBgUtil.setBg(360, Color.parseColor(ConfigureFile.ColorSystem)));
    }

    @Override
    protected void initData(Context mContext) {
        orderDetailMode = getViewModelProvider().get(OrderDetailMode.class);
    }

    @Override
    protected void loadMethod() {
        getPreData();
        setData();
        showBaseData();
        activityResult();
        couponRedEnvelopesResult();
        actualPaymentResult();
        isEnjoyActivity();
    }

    /**
     * 获取上一页传递过来的数据
     */
    private void getPreData() {
        oilPrice = getArguments().getString("oilPrice");
        orderAmount = AlgorithmUtil.getMultiplyAmount(getArguments().getString("amount"));
        memberType = getArguments().getString("memberType");
        isUseCoupon = getArguments().getString("isUseCoupon");
        memberCardId = getArguments().getString("memberCardId");
        memberId = getArguments().getString("memberId");
        productId = getArguments().getString("productId");
        productInfoId = getArguments().getString("productInfoId");
        usedOil = getArguments().getString("usedOil");
        paySwitch = getArguments().getString("paySwitch");
        parentId = getArguments().getString("parentId");
    }

    /**
     * 往Mode里面注入数据方便调用
     */
    private void setData() {
        orderDetailMode.setData(oilPrice, isUseCoupon, memberCardId, memberId, productId, productInfoId, orderAmount, usedOil, paySwitch, parentId);
    }

    /**
     * 显示从上一页传过来的本源数据
     */
    private void showBaseData() {
        tvOilsNums.setText(getArguments().getString("usedOil") + "");
        tvOrderAmount.setText(getArguments().getString("amount") + "元");
        tvSFAmount.setText("￥" + getArguments().getString("amount"));
        tvActivity.setText("暂无活动!");
        tvCouponSelect.setText("暂无优惠券可用！");
    }

    /**
     * 是否享受门店活动折扣
     */
    private void isEnjoyActivity() {
        if ("1".equals(memberType)) {
            getActivityList();
        } else {
            lyActivity.setVisibility(View.GONE);
            llCounpList.setVisibility(View.GONE);
        }
    }

    /**
     * 获取活动折扣
     */
    private void getActivityList() {
        map.put("activityType", "3");
        map.put("amount", orderAmount);
        map.put("memberId", memberId);
        map.put("payType", getArguments().getString("payType"));
        map.put("productId", getArguments().getString("productId"));
        map.put("storeId", DataUtil.getInstance().getStoreId());
        map.put("orderSource", "3");
        map.put("productInfoId", getArguments().getString("productInfoId"));
        orderDetailMode.getActivityList(getActivity(), map);
    }

    /**
     * 活动处理结果
     */
    private void activityResult() {
        orderDetailMode.getLiveDataActivity().observe(this, activityResultBean -> {
//            if (activityResultBean.getStateMsg().equals("有活动可选!")) {
//                lyActivity.setVisibility(View.VISIBLE);
//            } else {
//                lyActivity.setVisibility(View.GONE);
//            }
            tvActivity.setText(activityResultBean.getStateMsg());
        });
    }

    /**
     * 优惠券红包处理结果
     */
    private void couponRedEnvelopesResult() {
        orderDetailMode.getliveDataRedPage().observe(this, redPageResultBean -> {
            if (redPageResultBean.getCouponMsg().equals("暂无优惠券可用！")) {
                llCounpList.setVisibility(View.GONE);
            } else {
                llCounpList.setVisibility(View.VISIBLE);
                tvCouponSelect.setText(redPageResultBean.getCouponMsg());
            }

            if (redPageResultBean.getCpounNum() > 0) {
                tvCpounNum.setText(redPageResultBean.getCpounContent());
                tvCpounNum.setVisibility(View.VISIBLE);
            } else {
                tvCpounNum.setVisibility(View.GONE);
            }


        });
    }

    /**
     * 实付处理结果
     */
    private void actualPaymentResult() {
        orderDetailMode.getliveActualPayment().observe(this, amount -> {
            tvSFAmount.setText(amount);
        });
    }

    @OnClick({R.id.tv_pay, R.id.ll_view04, R.id.lyActivity})
    public void onViewClicked(View view) {
//        if (ThrottleFirstUtil.isFastClick()) {
//            Log.d("xxxxxaaa", "不可点击");
//            return;
//        }
        switch (view.getId()) {
            case R.id.tv_pay:
                tv_pay.setClickable(false);
                orderDetailMode.toPay(getActivity(), getArguments().getString("balance"), tvSFAmount.getText().toString());
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        //execute the task
                        try {
                            tv_pay.setClickable(true);
                        } catch (Exception e) {
                        }

                    }

                }, 5000);
                break;
            case R.id.ll_view04:
                startForResult(CouponListFragment.newInstance(getArguments().getString("productId"), memberId, orderAmount, memberCardId), 102);
                break;
            case R.id.lyActivity:
                SerializableMap Mymap = new SerializableMap();
                Mymap.setMap(map);
                startForResult(ActivityListFragment.newInstance(Mymap), 101);
                break;
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == 102) {
            ActivityBean activityBean = (ActivityBean) data.getSerializable("key");
            String activitySuperposition = activityBean.getSuperposition();
            if (!StringUtils.isEmpty(activitySuperposition)) {
                orderDetailMode.setPayAmount(activityBean, activityBean.getSuperposition(), getActivity());
                tvActivity.setText(activityBean.getActivityName());
            } else {
                ToastUtils.showToast(context.getApplicationContext(), "叠加活动数据异常！");
            }
        } else if (requestCode == 101 && resultCode == 103)//不使用活动
        {
            orderDetailMode.noUseActivty(getContext());
        } else if (requestCode == 102 && resultCode == 104)//优惠券
        {
            CouponChoseBean couponChoseBean = (CouponChoseBean) data.getSerializable("key");
            orderDetailMode.selectCoupon(couponChoseBean);
        }
    }


}
